<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-component">
      <el-form-item label="文件名">
        <el-input
          v-model="searchCondition.keyWord"
          placeholder="请输入文件名"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchCondition.createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        />
      </el-form-item>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="medium"
        @click="initLocalTable"
      >搜索</el-button>
      <el-button
        type="warning"
        icon="el-icon-refresh"
        size="medium"
        @click="resetSearchCondition"
      >重置</el-button>
    </el-form>
    <!-- 操作按钮 -->
    <el-form :inline="true" class="operation-component">
      <el-button
        type="primary"
        icon="el-icon-upload"
        size="mini"
        @click="showAddLocalForm"
      >上&nbsp;&nbsp;&nbsp;&nbsp;传</el-button>

      <el-button
        type="danger"
        icon="el-icon-delete"
        size="mini"
        @click="deleteLocal"
      >批量删除</el-button>
      <el-button
        type="success"
        icon="el-icon-download"
        size="mini"
        @click="exportLocal"
      >批量导出</el-button>
    </el-form>
    <!-- 列表 -->
    <el-table
      ref="localTable"
      :data="tableData"
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="文件名">
        <template slot-scope="{row}">
          <el-popover
            :content="'file/' + row.type + '/' + row.realName"
            placement="top-start"
            title="路径"
            width="200"
            trigger="hover"
          >
            <a
              slot="reference"
              :href="'http://localhost:8080' + '/file/' + row.type + '/' + row.realName"
              class="el-link--primary"
              style="word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"
              target="_blank"
            >
              {{ row.name }}
            </a>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="预览图">
        <template slot-scope="{row}">
          <el-image
            :src=" 'http://localhost:8080' + '/file/' + row.type + '/' + row.realName"
            :preview-src-list="[baseApi + '/file/' + row.type + '/' + row.realName]"
            fit="contain"
            lazy
            class="el-avatar"
          >
            <div slot="error">
              <i class="el-icon-document" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="suffix" label="文件类型" />
      <el-table-column prop="type" label="类别" />
      <el-table-column prop="size" label="大小" />
      <el-table-column prop="createBy" label="操作人" />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="width"
        sortable
      />
      <el-table-column label="操作" width="width" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="small"
            @click="showUpdateLocalForm(row)"
          >修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="row.localId === 1"
            @click="deleteLocal(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      :current-page="page.current"
      :total="page.total"
      :page-size="page.size"
      :page-sizes="[10, 20, 50, 100]"
      style="padding: 20px 0"
      layout="total,prev, pager, next, sizes,jumper"
      @current-change="initLocalTable"
      @size-change="handleSizeChange"
    />
    <!-- 新增/修改表单 -->
    <el-dialog
      :title="local.localId ? '修改文件' : '上传文件'"
      :visible.sync="dialogFormVisible"
      width="20%"
    >
      <el-form ref="localForm" :model="local" label-width="80px">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="local.name" />
        </el-form-item>
        <!--   上传文件   -->
        <el-form-item v-if="!local.storageId" label="上传">
          <el-upload
            ref="upload"
            drag
            :limit="1"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :headers="headers"
            :on-success="handleSuccess"
            :on-error="handleError"
            :action="fileUploadApi + '?name=' + local.name"
          >
            <div class="eladmin-upload"><i class="el-icon-upload" /> </div>
            <div style="color:#1890ff">添加文件</div>
            <div slot="tip" class="el-upload__tip">可上传任意格式文件，但不可超过10M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="!local.storageId" type="primary" @click="upload">确 定</el-button>
        <el-button v-else type="primary" @click="saveDialogForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Config from '@/settings'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  name: 'Local',
  data() {
    return {
      page: {
        total: 0, // 总记录数
        current: 1, // 当前页码
        size: 10, // 每页记录数
        orders: [{ column: 'id', asc: true }]
      },
      searchCondition: {
        createTime: [],
        keyWord: ''
      },
      tableData: [], // 列表数据
      dialogFormVisible: false, // 是否展示新增/修改表单
      selectedIds: [], // 所有选择的id的数组
      local: {
        storageId: undefined,
        name: ''
      }, // 当前要操作的local
      headers: { 'Authorization': getToken() },
      loading: false
    }
  },
  mounted() {
    this.initLocalTable()
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    async initLocalTable(current = 1) {
      const { page, searchCondition } = this
      if (Number.isInteger(current)) {
        page.current = current
      }
      const result = await this.$API.localStorage.pageQuery({ searchCondition, page })
      if (result.code === 200) {
        this.tableData = result.data.records
        this.page.current = result.data.current
        this.page.size = result.data.size
        this.page.total = result.data.total
      }
    },
    resetSearchCondition() {
      this.searchCondition.createTime = []
      this.searchCondition.keyWord = ''
      this.initLocalTable()
    },
    async deleteLocal(row) {
      let localIds = []
      if (row.storageId) {
        localIds = [row.storageId]
      } else {
        localIds = this.selectedIds
      }
      if (localIds.length === 0) {
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning',
          showClose: true,
          duration: Config.duration
        })
        return
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const result = await this.$API.localStorage.deleteStorage(localIds)
          if (result.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
              showClose: true,
              duration: Config.duration
            })
            this.initLocalTable()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showAddLocalForm() {
      this.local.name = ''
      this.dialogFormVisible = true
    },
    async showUpdateLocalForm(row) {
      this.local.storageId = row.storageId
      this.local.name = row.name
      this.dialogFormVisible = true
    },
    upload() {
      this.$refs.upload.submit()
    },
    async saveDialogForm() {
      const result = await this.$API.localStorage.updateStorage(this.local)
      if (result.code === 200) {
        this.$message({
          message: '修改成功',
          type: 'success',
          showClose: true,
          duration: Config.duration
        })
        this.initLocalTable()
        this.dialogFormVisible = false
      } else {
        this.$message({
          message: '修改失败',
          type: 'error',
          showClose: true,
          duration: Config.duration
        })
      }
    },
    /*
      列表选中状态发生改变的监听回调
    */
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.localId)
    },
    /*
    处理pageSize发生改变的监听回调
    */
    handleSizeChange(pageSize) {
      this.page.size = pageSize
      this.initLocalTable()
    },
    async exportLocal() {
      await this.$API.localStorage.exportLocal(this.selectedIds)
    },
    handleSuccess() {
      this.$message({
        message: '上传成功',
        type: 'success',
        showClose: true,
        duration: Config.duration
      })
      this.$refs.upload.clearFiles()
      this.initLocalTable()
      this.dialogFormVisible = false
    },
    handleError() {
      this.$message({
        message: '上传失败',
        type: 'error',
        showClose: true,
        duration: Config.duration
      })
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message({
          message: '上传文件大小不能超过 10MB!',
          type: 'error',
          showClose: true,
          duration: Config.duration
        })
      }
      this.local.name = file.name
      return isLt2M
    }
  }
}
</script>

<style scoped>
</style>
